<?php

declare(strict_types=1);

namespace App\Controller\Admin;

use App\Model\Admin\Admin;
use App\Model\Bill;
use App\Model\CashLog;
use App\Model\Station;
use Hyperf\DbConnection\Db;
use Hyperf\Redis\Redis;
use Hyperf\HttpServer\Contract\RequestInterface;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use Psr\Container\ContainerExceptionInterface;
use Psr\Container\NotFoundExceptionInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\SimpleCache\InvalidArgumentException;
use RedisException;
use Trait\ResponseMsg;
use App\Model\Normal;
use Hyperf\Di\Annotation\Inject;
use Util\Common;
use App\Controller\AbstractController;
use App\Model\Distributors;

class ProfitController extends AbstractController
{
    use ResponseMsg;

    protected Redis $redis;
    protected Normal $normal;
    #[Inject]
    protected Admin $admin;

    public function __construct()
    {
        $this->redis = container()->get(Redis::class);
        $this->normal = container()->get(Normal::class);
    }

    /**提现记录
     * @param RequestInterface $request
     * @return ResponseInterface
     */
    public function outCash(RequestInterface $request):ResponseInterface{
        $page = $request->inputs(['page','limit','cash_type',
            'distributor_id','time', 'status','is_return']);
        $data['list'] = Db::table('cash_log as c')
            ->leftJoin('distributors as d', 'c.distributor_id','=','d.id')
            ->where(function ($query) use ($page) {
                if($page['distributor_id']){
                    $query->where('c.distributor_id',$page['distributor_id']);
                }
                if($page['cash_type']){
                    $query->where('c.cash_type',$page['cash_type']);
                }
                if($page['status']){
                    $query->where('c.status',$page['status']);
                }
                if($page['is_return'] != ''){
                    $query->where('c.is_return',$page['is_return']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('c.created_at', '>=', $page['time'][0]);
                    $query->where('c.created_at', '<=', $page['time'][1]);
                }
            })->orderBy( 'id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('c.*','d.name')
            ->get();
        $data['total'] = Db::table('cash_log as c')
            ->leftJoin('distributors as d', 'c.distributor_id','=','d.id')
            ->where(function ($query) use ($page) {
                if($page['distributor_id']){
                    $query->where('c.distributor_id',$page['distributor_id']);
                }
                if($page['status']){
                    $query->where('c.status',$page['status']);
                }
                if($page['cash_type']){
                    $query->where('c.cash_type',$page['cash_type']);
                }
                if($page['is_return'] != ''){
                    $query->where('c.is_return',$page['is_return']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('c.created_at', '>=', $page['time'][0]);
                    $query->where('c.created_at', '<=', $page['time'][1]);
                }
            })->count();
        return $this->success($data);
    }

    /**分润流水记录
     * @param RequestInterface $request
     * @return ResponseInterface
     * @throws ContainerExceptionInterface
     * @throws NotFoundExceptionInterface
     */
    public function getList(RequestInterface $request):ResponseInterface
    {
        $page = $request->inputs(['page','limit', 'distributor_id','time']);
        $info = $this->admin->getInfo($request);
        $data['list'] = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page,$info) {
                $query->where('account_type',1);
                if ($page['distributor_id']) {
                    $query->where('b.account_id', $page['distributor_id']);
                } else {
                    if (isset($info['distributor_id'])) {
                        $query->where('b.account_id', $info['distributor_id']);
                    } else {
                        $query->where('b.account_id', '>', 0);
                    }
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('b.id', 'desc')
            ->offset(($page['page'] - 1) * $page['limit'])
            ->limit($page['limit'])
            ->select('b.*', 'o.number as order_number','o.sn','o.channel_number','d.name','d.rate','o.station_id')
            ->get();
        $data['total'] = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page,$info) {
                $query->where('account_type',1);
                if ($page['distributor_id']) {
                    $query->where('b.account_id', $page['distributor_id']);
                } else {
                    if (isset($info['distributor_id'])) {
                        $query->where('b.account_id', $info['distributor_id']);
                    } else {
                        $query->where('b.account_id', '>', 0);
                    }
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->count();
        return $this->success($data);
    }


    public function exportBill(RequestInterface $request){
        try{
        $page = $request->input('search');
        $page = json_decode($page,true);
        $data['list'] = Db::table('bills as b')
            ->leftJoin('orders as o', 'b.target_id','=','o.id')
            ->leftJoin('distributors as d', 'b.account_id','=','d.id')
            ->where(function ($query) use ($page) {
//                if (array_key_exists('keyword',$page) && $page['keyword']) {
//                    $query->where('o.number', '%'.$page['keyword'] . '%');
//                $query->orWhere('o.out_ord_id', 'like', '%'.$page['keyword'].'%');
//                }
                $query->where('account_type','App\Model\Distributors');
                if($page['stationsId']){
                    $query->whereIn('o.station_id',$page['stationsId']);
                }else{
                    if($page['distributor_id']){
                        $query->where('b.account_id',$page['distributor_id']);
                    }
                }
                if($page['payment_type']){
                    $query->where('o.payment_type',$page['payment_type']);
                }
                if (isset($page['time']) && is_array($page['time'])) {
                    $query->where('o.created_at', '>=', $page['time'][0]);
                    $query->where('o.created_at', '<=', $page['time'][1]);
                }
            })->orderBy('b.id', 'desc')
            ->select('b.*', 'o.number as order_number','o.sn','o.channel_number','d.name','d.rate','o.station_id','o.use_fee','o.charge_service')
            ->get();
        $data['list'] = json_encode($data['list']);
        $data['list'] = json_decode($data['list'],true);
        foreach($data['list'] as $k => $v){
            $data['list'][$k]['station'] = Station::find($v['station_id']);
            switch ($data['list'][$k]['payment_type']){
                case 'balance':
                    $data['list'][$k]['payment'] = '余额';
                    break;
                case 'wx_lite':
                    $data['list'][$k]['payment'] = '微信';
                    break;
                default:
                    $data['list'][$k]['payment'] = '支付宝';
                    break;

            }
        }
            $spreadsheet = new Spreadsheet();
            $sheet = $spreadsheet->getActiveSheet();
            // 设置 Excel 文档的头部
            $sheet->setCellValue('A1', '订单号');
            $sheet->setCellValue('B1', '经销商');
            $sheet->setCellValue('C1', '站点');
            $sheet->setCellValue('D1', '付款方式');
            $sheet->setCellValue('E1', '分成比例');
            $sheet->setCellValue('F1', '订单电费&服务费');
            $sheet->setCellValue('G1', '分润金额');
            $sheet->setCellValue('H1', '创建时间');
            $sheet->setCellValue('I1', '余额');
            foreach (range('A', 'O') as $columnID) {
                $sheet->getColumnDimension($columnID)->setAutoSize(true);
            }

// 设置单元格水平居中的样式数组配置
            $styleArray = [
                'alignment' => [
                    'horizontal' => \PhpOffice\PhpSpreadsheet\Style\Alignment::HORIZONTAL_CENTER,
                ],
            ];

// 应用样式到第一行的A到O列
            $sheet->getStyle('A:O')->applyFromArray($styleArray);
            // 从第二行开始填充订单数据
            $row = 2;
            foreach ($data['list'] as $order) {
                $sheet->setCellValue('A' . $row, $order['number'] . ' ');
                $sheet->setCellValue('B' . $row, $order['name']);
                $sheet->setCellValue('C' . $row, $order['station']['name']);
                $sheet->setCellValue('D' . $row, $order['payment']);
                $sheet->setCellValue('E' . $row, $order['rate']);
                $sheet->setCellValue('F' . $row, '电费'.$order['use_fee'].'+服务费'.$order['charge_service']);
                $sheet->setCellValue('G' . $row, $order['fee']);
                $sheet->setCellValue('H' . $row, $order['created_at']);
                $sheet->setCellValue('I' . $row, $order['balance']);
                $row++;
            }
            // 将 Spreadsheet 对象写入 XLSX 文件
            $writer = new Xlsx($spreadsheet);
            // 创建临时文件
            $publicPath = BASE_PATH . '/public/upload/xls/';
            $fileName = date('YmdHis', time()) . '-bills.xlsx';
//        $temp_file = tempnam(sys_get_temp_dir(), $fileName);
            $temp_file = $publicPath . $fileName;
            // 保存到临时文件
            $writer->save($temp_file);
            return $this->success(['url' => Common::MAIN_HOST . '/upload/xls/' . $fileName]);

        }catch (\Exception $e){
            return $this->error(1001,$e->getMessage());
        }

    }

}
